﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Intel_Client_GUI.ServiceReference1;
using System.Windows.Media.Imaging;
using System.IO;
using Microsoft.Expression.Interactivity.Core;
using System.Windows.Input;
namespace Intel_Client_GUI
{
	public class PluginDownloaderViewModel : INotifyPropertyChanged
	{

        public delegate void SetInfosCB(object paramter, int uuid);

        private object uuid_lock = new object();

        private int _uuid=-1;
		
		
		
		public PluginDownloaderViewModel()
		{
			// 在此点下面插入创建对象所需的代码。
			this.AddPlugin = new ActionCommand(this.AddPluginCmd);
            if (!GuiDir.Exists)
                GuiDir.Create();
            if (!BackDir.Exists)
                BackDir.Create();
		}
        

        public ICommand AddPlugin
        {
            get;
            private set;
        }
        private void AddPluginCmd(object selectItem)
        {
            FileInfo file;
            var si = selectItem as PluginInfo;
            if (si.Type == PluginType.Gui)
            {
                file = new FileInfo(GuiDir.FullName + '\\' + si.Uuid.ToString() + '-' + si.Name.ToString() + ".dll");

            }
            else
                file = new FileInfo(BackDir.FullName + '\\' + si.Uuid.ToString() + '-' + si.Name.ToString() + ".dll");
            if (file.Exists)
            {
                System.Windows.MessageBox.Show("Plugin is alreay existed");
            }
            try
            {
                var Client = new PluginServerClient();
                var s = Client.GetPlugin(si.Uuid);
                FileStream fs = new FileStream(file.FullName, FileMode.Create, FileAccess.ReadWrite);
                s.CopyTo(fs);
                fs.Close();
                s.Close();
                Client.Close();
                Globle.Pm.LoadPlugin(file.FullName);
            }
            catch (System.Exception ex)
            {
                this.ErrorInfo = ex.Message;
            }
            System.Windows.MessageBox.Show(file.FullName);

        }


		public PluginInfo[] PluginsList
		{
			get
			{
                return this.pluginsList;
			}
			set
			{
				this.pluginsList = value;
				this.NotifyPropertyChanged("PluginsList");
			}
		}
        private PluginInfo[] pluginsList;


		public string ErrorInfo
		{
			get{return this.errorInfo;}
			set{this.errorInfo=value;this.NotifyPropertyChanged("ErrorInfo");}
		}
        private string errorInfo;


        public BitmapSource DetailImageSource
        {
            get
            {
                return detailImage;
            }
            set { detailImage = value; this.NotifyPropertyChanged("DetailImageSource"); }
        }
        private BitmapSource detailImage;


		public PluginInfo SelectedInfo
		{
			get{return this.selectedInfo;}
            set 
            {
                this.selectedInfo = value;
                this.NotifyPropertyChanged("SelectedInfo");
                var id = value.Uuid;
                lock (this.uuid_lock)
                {
                    _uuid = id;
                }
                this.DetailImageSource = null;
                this.BeginGetImage(id);
            }
		}
		private PluginInfo selectedInfo;
		
		public void BeginGetList()
		{
			Action<object> GetInfosAsync =delegate(object p1)
			{
                try
                {
                    var Client = new PluginServerClient();
                    this.PluginsList = Client.GetPluginsList();
                }
                catch (System.Exception ex)
                {
                    this.ErrorInfo = ex.Message;
                }
			};
			GetInfosAsync.BeginInvoke(null,null,null);
		}

        public void BeginGetImage(int uuid)
        {
            //Action
            Action<object> GetInfosAsync = delegate(object p1)
            {
                SetInfosCB SetSource = delegate(object s, int pid)
                {
                    var ImageSource = new System.Windows.Media.Imaging.BitmapImage();
                    ImageSource.BeginInit();
                    ImageSource.StreamSource = s as Stream;
                    ImageSource.EndInit();
                    lock (this.uuid_lock)
                    {
                        //if (pid != this._uuid)
                          //  return;
                        this.DetailImageSource = ImageSource;
                    }
                };
                try
                {
                    int pid = (int)p1;
                    var Client = new PluginServerClient();
                    var s = Client.GetPic(pid);
                    Stream ms = new MemoryStream();
                    s.CopyTo(ms);
                    s.Close();
                    Client.Close();
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    App.Current.Dispatcher.BeginInvoke(SetSource, ms, null);
                }
                catch (System.Exception ex)
                {
                    this.ErrorInfo = ex.Message;
                }
            };
            GetInfosAsync.BeginInvoke(uuid, null, null);
        }
		
		


        private DirectoryInfo GuiDir = new DirectoryInfo("GuiAddons");

        private DirectoryInfo BackDir = new DirectoryInfo("BackgroudAddons");

		#region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;


        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
				
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
	}
}